<script setup lang="ts">
import type { PaginationProps, TableProps } from 'ant-design-vue'
import { CommTablePagination, CommTableSize } from '~/components/comm-table/comm-table-data.ts'
import type { Page } from '~/api/base/base-model.ts'
import type { PermissionReq, PermissionResp } from '~/api/setting/model/permission.ts'
import { PermissionModalTableColumns } from '~/pages/setting/datas/role-data.ts'
import { queryPermissionCheckedPageOfRoleId } from '~/api/setting/permission.ts'
import type { RolePermissionReq } from '~/api/setting/model/role-permission.ts'
import { bindRolePermissionRelationApi, unBindRolePermissionRelationApi } from '~/api/setting/role.ts'

const props = defineProps({
  roleData: Object,
})

const emits = defineEmits(['onAuthSuccess'])

const message = useMessage()

const tableSize = shallowRef<string[]>(CommTableSize)

const columns = PermissionModalTableColumns
const loading = shallowRef(false)

const pageSource = shallowRef<Page<PermissionResp>>({})
const dataSource = shallowRef<PermissionResp[]>([])

type Key = string | number
const permissionSelectedRowKeys = shallowRef<Key[]>([])

const pagination = reactive<PaginationProps>({
  ...CommTablePagination,
  total: pageSource.value?.total,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})

const formQuery = reactive<PermissionReq>({
  roleId: props?.roleData?.id,
  permissionNameByLike: undefined,
})

async function init() {
  if (loading.value) {
    return
  }
  loading.value = true
  try {
    pageSource.value = await queryPermissionCheckedPageOfRoleId({
      param: formQuery,
      current: pagination.current,
      size: pagination.pageSize,
    })
    dataSource.value = pageSource.value?.records ?? []

    permissionSelectedRowKeys.value = []
    if (dataSource.value && dataSource.value.length > 0) {
      for (const permissionResp of dataSource.value) {
        if (permissionResp.checked && permissionResp.id) {
          permissionSelectedRowKeys.value.push(permissionResp.id)
        }
      }
    }
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
  }
}

async function onSearch() {
  pagination.current = 1
  await init()
}

function onTableRowSelect(record: PermissionResp, selected) {
  if (selected) {
    authPermission(record)
  } else {
    unAuthPermission(record)
  }
}

function onTableRowChange(selectedRowKeys: Key[]) {
  console.log('selectedRowKeys changed: ', selectedRowKeys)
  permissionSelectedRowKeys.value = selectedRowKeys
}

async function onClose() {
  emits('onAuthSuccess')
}

/**
 * 授权功能
 *
 * @param permissionResp
 */
async function authPermission(permissionResp: PermissionResp) {
  const close = message.loading('授权中......')
  try {
    const rolePermissionReq: RolePermissionReq = {
      roleId: props?.roleData?.id,
      permissionId: permissionResp.id,
    }
    const isAuth = await bindRolePermissionRelationApi(rolePermissionReq)
    if (isAuth) {
      message.success('授权成功')
    }
  } catch (e) {
    console.log(e)
  } finally {
    close()
  }
}

/**
 * 解除授权功能
 *
 * @param permissionResp
 */
async function unAuthPermission(permissionResp: PermissionResp) {
  const close = message.loading('取消授权中......')
  try {
    const rolePermissionReq: RolePermissionReq = {
      roleId: props?.roleData?.id,
      permissionId: permissionResp.id,
    }
    const isAuth = await unBindRolePermissionRelationApi(rolePermissionReq)
    if (isAuth) {
      message.success('授权取消成功')
    }
  } catch (e) {
    console.log(e)
  } finally {
    close()
  }
}

onMounted(() => {
  init()
})
</script>

<template>
  <a-modal
    title="授权权限"
    width="1000px"
    footer=""
    @close="onClose"
  >
    <a-input-search
      v-model:value="formQuery.permissionNameByLike"
      placeholder="请输入权限名称"
      enter-button="搜索"
      class="input-search"
      @search="onSearch"
    />
    <a-table
      :row-selection="{ selectedRowKeys: permissionSelectedRowKeys,
                        onChange: onTableRowChange,
                        onSelect:
                          onTableRowSelect,
                        getCheckboxProps: (record: PermissionResp) => ({
                          // Column configuration not to be checked
                          disabled: record.stateId === 0 && !record.checked,
                        }) }"
      :loading="loading"
      row-key="id"
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :size="tableSize[0] as TableProps['size']"
    >
      <template #bodyCell="scope">
        <template v-if="scope?.column?.dataIndex === 'indexNo'">
          {{ scope?.index + 1 }}
        </template>
        <template v-if="scope?.column?.dataIndex === 'permissionName'">
          <a-tag :color="scope?.record?.stateId === 1 ? 'green' : 'red'">
            {{ scope?.record?.stateId === 1 ? '有效' : '无效' }}
          </a-tag>
          {{ scope?.record?.permissionName }}
        </template>
      </template>
    </a-table>
  </a-modal>
</template>

<style lang="less" scoped>
.input-search {
  margin-bottom: 16px;
  width: 300px;
}
</style>
